/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.adira.fraud.hibernate;

import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
 * Hibernate Utility class with a convenient method to get Session Factory
 * object.
 *
 * @author 12031475
 */
public class HibernateUtil {
/*
	private static final SessionFactory sessionFactory;

	  static{

		  try{
	
		  sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
	
		  }catch(Throwable th){
	
		  System.err.println("Enitial SessionFactory creation failed"+th);
	
		  throw new ExceptionInInitializerError(th);
	
		  }

	  }

	  public static SessionFactory getSessionFactory(){

		  return sessionFactory;

	  }
	*/
	
	private static final SessionFactory sessionFactory;
	//private static final Session hibernateSession ;
	static {
	try {
			// Create the SessionFactory from standard (hibernate.cfg.xml)
			// config file.
			sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
			
		} catch (Throwable ex) {
			// Log the exception.
			System.err.println("Initial SessionFactory creation failed." + ex);
		throw new ExceptionInInitializerError(ex);
		}
	}
	 
	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	 
	public static Session beginTransaction() {
		Session hibernateSession = HibernateUtil.getSession();
		hibernateSession.beginTransaction();
		return hibernateSession;
	}
	 
	public static void commitTransaction() {
		HibernateUtil.getSession().getTransaction().commit();
	}
	 
	public static void rollbackTransaction() {
		HibernateUtil.getSession().getTransaction().rollback();
	}
	 
	public static void closeSession() {
		HibernateUtil.getSession().close();
	}
	 
	public static Session getSession() {
		return sessionFactory.getCurrentSession();
	}
	
	public static void closeAll(org.hibernate.Session session, org.hibernate.Transaction tr) {
		if(tr.isActive()){
			tr.commit();
		}
		if(session.isOpen()){
			session.close();
		}
	}
	
}
